package cn.wolfcode.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 鉴权拦截器:
 * 做登录判断, 如果带了token 表示要进行登录鉴权, 没有token表示直接放行
 */
@Component
public class AuthZuulFilter  extends ZuulFilter {
    //过滤器的类型
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    //过滤器的序号(优先级)
    //优先级越小先执行
    @Override
    public int filterOrder() {
        return 1;
    }

    //是否执行鉴权过滤, true表示当前请求要执行鉴权操作, false表示当前请求不执行鉴权操作
    @Override
    public boolean shouldFilter() {
        //做登录判断, 如果带了token 表示要进行登录鉴权, 没有token表示直接放行
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String token = request.getHeader("token");
        return StringUtils.hasLength(token);
    }

    //鉴权操作逻辑, 执行前提:shouldFilter() 返回true时候
    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        //执行token鉴权
        System.out.println("执行token鉴权........................");
        //不放行, 不转发
        requestContext.setSendZuulResponse(false);
        //响应状态
        requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        try {
            //响应内容
            requestContext.getResponse().getWriter().write("no unauthorized");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //不携带数据
        return null;
    }
}
